package com.tssup.fesco.common.frame.event;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;

/**
 * 事件服务类
 *
 * @author daqing
 */
public class EventBusService {

    public final static EventBusService service = new EventBusService();

    private static final Logger log = LoggerFactory.getLogger(EventBusService.class.getName());

    static final int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;

    private EventBus eventBus = null;
    private EventBus asyncBus = null;

    private EventBusService() {
        this.asyncBus = new AsyncEventBus(Executors.newCachedThreadPool());
        this.eventBus = new EventBus();
    }

    /**
     * 调用eventBus.register时，会向eventBus中注册一个Listener。这里的listener就是EventSubscriber子类实例
     *
     * @param subscriber
     * @param isAsyn
     */
    public void register(EventSubscriber subscriber, Boolean isAsyn) {

        log.info("向eventBus中注册一个Listener[" + subscriber.toString() + "]");

        if (isAsyn) {
            this.asyncBus.register(subscriber);
        } else {
            this.eventBus.register(subscriber);
        }
    }

    public void unregister(EventSubscriber subscriber, Boolean isAsyn) {
        if (isAsyn) {
            this.asyncBus.unregister(subscriber);
        } else {
            this.eventBus.unregister(subscriber);
        }
    }

    /**
     * Posts an event to all registered subscribers.
     *
     * @param event
     */
    public void fire(EventSource event) {
        eventBus.post(event);
    }

    public void asyncFire(EventSource event) {
        asyncBus.post(event);
    }

}
